package com.example.experimen2;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import com.example.experimen2.constraint.Constraint;

import java.util.HashMap;

public class GameSound {

    private Context context;

    // 音效的音量
    private int streamVolume;
    private SoundPool soundPool;
    private HashMap<String, Integer> soundIdMap = new HashMap<String, Integer>();
    private int gameBGMStreamId;

    private static GameSound instance;

    public GameSound(Context context) {
        this.context = context;
    }

    public static GameSound getInstance(MainActivity context) {
        if (instance == null) {
            instance = new GameSound(context);
        }
        return instance;
    }

    public void loadSound() {
        soundPool = new SoundPool.Builder()
                .setMaxStreams(3)//传入最多播放音频数量
                .build();
        soundIdMap.put(Constraint.CONNECT_FAILED, soundPool.load(context, R.raw.connect_failed, 1));
        soundIdMap.put(Constraint.CONNECT_SUCCESS, soundPool.load(context, R.raw.connect_succcess, 1));
        soundIdMap.put(Constraint.WIN, soundPool.load(context, R.raw.win, 1));
        soundIdMap.put(Constraint.LOSE, soundPool.load(context, R.raw.lose, 1));
        soundIdMap.put(Constraint.GAME_BGM, soundPool.load(context, R.raw.game_bgm, 1));

        // 获得声音设备和设备音量
        AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);

    }

    public void playGameBGM() {
        //播放音乐BGM
        //异步需要等待加载完成，音频才能播放成功
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                if (status == 0) {
                    //第一个参数soundID
                    //第二个参数leftVolume为左侧音量值（范围= 0.0到1.0）
                    //第三个参数rightVolume为右的音量值（范围= 0.0到1.0）
                    //第四个参数priority 为流的优先级，值越大优先级高，影响当同时播放数量超出了最大支持数时SoundPool对该流的处理
                    //第五个参数loop 为音频重复播放次数，0为值播放一次，-1为无限循环，其他值为播放loop+1次
                    //第六个参数 rate为播放的速率，范围0.5-2.0(0.5为一半速率，1.0为正常速率，2.0为两倍速率)
                    gameBGMStreamId = soundPool.play(soundIdMap.get(Constraint.GAME_BGM), streamVolume, streamVolume, 1, -1, 1);
                }
            }
        });
    }

    public void playSound(String soundName) {
        // 根据soundName，从事先加载好的音效Map中取出对应的soundID
        // 播放指定的音效
        soundPool.play(soundIdMap.get(soundName), streamVolume, streamVolume, 0, 0, 1);
    }

    public void stopGameBGM() {
        //游戏结束，停止播放游戏背景音乐
        soundPool.stop(gameBGMStreamId);
    }

    public void release() {
        //释放音效资源
        soundPool.release();
    }


}
